/*
    SUSAN® - Sole of Unix Save ANything

   Copyright (C) 2018-2020 Hechzh Property

   
*/

#include "include/susan.h"
#include "console/console_conf.h"
#include "console/console_globals.h"
#include "console/console_output.h"
#include "console/console_conf.h"
#include "include/jcr.h"
#include "lib/qualified_resource_name_type_converter.h"
#include "lib/bstringlist.h"
#include "lib/bsock_tcp.h"

namespace console {
SusanSocket* ConnectToDirector(JobControlRecord& jcr,
                                utime_t heart_beat,
                                BStringList& response_args,
                                uint32_t& response_id)
{
  SusanSocketTCP* UA_sock = new SusanSocketTCP;
  if (!UA_sock->connect(NULL, 5, 15, heart_beat, "Director daemon",
                        director_resource->address, NULL,
                        director_resource->DIRport, false)) {
    delete UA_sock;
    UA_sock = nullptr;
    return nullptr;
  }
  jcr.dir_bsock = UA_sock;

  const char* name;
  s_password* password = NULL;

  TlsResource* local_tls_resource;
  if (console_resource) {
    name = console_resource->resource_name_;
    ASSERT(console_resource->password.encoding == p_encoding_md5);
    password = &console_resource->password;
    local_tls_resource = console_resource;
  } else { /* default console */
    name = "*UserAgent*";
    ASSERT(director_resource->password_.encoding == p_encoding_md5);
    password = &director_resource->password_;
    local_tls_resource = director_resource;
  }

  if (local_tls_resource->IsTlsConfigured()) {
    std::string qualified_resource_name;
    if (!my_config->GetQualifiedResourceNameTypeConverter()->ResourceToString(
            name, my_config->r_own_, qualified_resource_name)) {
      delete UA_sock;
      UA_sock = nullptr;
      jcr.dir_bsock = nullptr;
      return nullptr;
    }

    if (!UA_sock->DoTlsHandshake(TlsPolicy::kBnetTlsAuto, local_tls_resource,
                                 false, qualified_resource_name.c_str(),
                                 password->value, &jcr)) {
      delete UA_sock;
      UA_sock = nullptr;
      jcr.dir_bsock = nullptr;
      return nullptr;
    }
  } /* IsTlsConfigured */

  std::string own_qualified_name = "R_CONSOLE::";
  own_qualified_name += name;

  if (!UA_sock->ConsoleAuthenticateWithDirector(
          &jcr, name, *password, director_resource, own_qualified_name,
          response_args, response_id)) {
    delete UA_sock;
    UA_sock = nullptr;
    jcr.dir_bsock = nullptr;
    return nullptr;
  }
  return UA_sock;
}

} /* namespace console */
